package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.multi_image_selector.MultiImageSelectorActivity;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.NewInteractionAtlasSeeActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.page.chat.MomentsPage;
import com.shwread.android.ui.widget.NewInteractionContentView;
import com.shwread.android.ui.widget.toast.LoadToast;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.Log;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.constants.DefaultConsts;
import logic.util.ImageLoaderUtil;
import logic.util.Utils;


/**
 * @author xuzhijun
 * @date 2015年5月6日下午3:07:10
 */
public class NewInteractionCenterUserPublishPage
        extends
        AbstractUIPage<BaseBusinessActivity>
        implements
        OnClickListener
{
	
	private static final int                           REQUEST_IMAGE      = 2;
	private final int                                  PIC_MAX_LENGTH     = 6;
	
	private Context                                    mContext;
	//Title
	private TextView                                   tvTitle;
	private Button                                     btnBack;
	private Button                                     btnSubmit;
	
	//
	private ImageView                                  addFriend;
	private EditText                                   edtContent;
	private LinearLayout                               friendLL;
	private ArrayList<String>                          mSelectPath;
	//	private LoadingDialog         loadingDialog;
	private int                                        height;
	private List<FriendImageView>                      listFriend         = new ArrayList<FriendImageView>();
	private ArrayList<String>                          selectedPictureAll = new ArrayList<String>();
	private InputMethodManager                         inputMethodManager;
	private static NewInteractionCenterUserPublishPage instance;
	
	public static NewInteractionCenterUserPublishPage getInstance(BaseBusinessActivity t) {
		/* if (null == instance) */instance = new NewInteractionCenterUserPublishPage(t);
		return instance;
	}
	
	public NewInteractionCenterUserPublishPage(BaseBusinessActivity t) {
		super(t);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		mContext = bActivity;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.new_interaction_center_user_publish, null);
		inputMethodManager = (InputMethodManager) bActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		initView();
		initData();
		initListener();
		
		return curMyView;
	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		edtContent.requestFocus();
		inputMethodManager.showSoftInput(edtContent, InputMethodManager.RESULT_UNCHANGED_SHOWN);
		return 0;
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		// TODO Auto-generated method stub
		closeToast(0);
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		switch (arg0) {
		
			case REQUEST_IMAGE:
				if (MultiImageSelectorActivity.dataForBefore == null) return;
				arg1 = MultiImageSelectorActivity.dataForBefore.getExtras();
				mSelectPath = arg1.getStringArrayList(MultiImageSelectorActivity.EXTRA_RESULT);
				mSelectPath.removeAll(selectedPictureAll);
				selectedPictureAll.addAll(mSelectPath);
				for (String p : mSelectPath)
				{
					FriendImageView friendImageView = new FriendImageView(p);
					friendLL.addView(friendImageView.getFriendView(), friendLL.getChildCount() - 1);
					listFriend.add(friendImageView);
				}
				notyPicChange();
				
				break;
			
			default:
				break;
		}
		
	}
	
	@Override
	public void setStatus(int arg0) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		// TODO Auto-generated method stub
		return null;
	}
	
	//	@Override
	//	protected void onCreate(Bundle savedInstanceState) {
	//		super.onCreate(savedInstanceState);
	//		setContentView(R.layout.new_interaction_center_user_publish);
	//		mContext = this;
	//		initView();
	//		initData();
	//		initListener();
	//	}
	//	
	//	private Handler handler = new Handler()
	//	                        {
	//		                        @Override
	//		                        public void handleMessage(Message msg) {
	//			                        
	//		                        }
	//	                        };
	//	
	//	@Override
	//	public Handler getUIHandler() {
	//		return handler;
	//	}
	//	
	private void initView() {
		//Title		
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setVisibility(View.GONE);
		btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		btnSubmit = (Button) curMyView.findViewById(R.id.common_header_publish);
		btnSubmit.setVisibility(View.VISIBLE);
		//		btnSubmit.setText("发布");
		
		addFriend = (ImageView) curMyView.findViewById(R.id.new_interation_center_user_publish_add_friend_img);
		edtContent = (EditText) curMyView.findViewById(R.id.new_interation_center_user_publish_cotent_tv);
		
		friendLL = (LinearLayout) curMyView.findViewById(R.id.new_interation_center_user_publish_at_friend_ll);
	}
	
	private void initData() {
		//		loadingDialog = new LoadingDialog(mContext);
		WindowManager manager = bActivity.getWindowManager();
		Display display = manager.getDefaultDisplay();
		height = display.getHeight();
		
	}
	
	private void initListener() {
		btnBack.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		addFriend.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		new Thread(new Runnable()
		{
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//				Util.hideInputMethodManager(mContext, edtContent);
				inputMethodManager.hideSoftInputFromWindow(edtContent.getWindowToken(), 0);
			}
		}).start();
		
		switch (v.getId()) {
			case R.id.common_header_back:
				bActivity.onBackPressed();
				break;
			case R.id.common_header_publish:
				//				Utils.ToastShow(mContext, "发送");
				submit();
				break;
			case R.id.new_interation_center_user_publish_add_friend_img:
				Intent intent = new Intent(bActivity, MultiImageSelectorActivity.class);
				// 是否显示拍摄图片
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
				// 最大可选择图片数量
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, PIC_MAX_LENGTH);
				// 选择模式
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
				// 默认选择
				if (selectedPictureAll != null && selectedPictureAll.size() > 0)
				{
					intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
				}
				bActivity.startActivityForResult(intent, REQUEST_IMAGE);
				break;
		}
	}
	
	private void submit() {
		String[] picPATHs = selectedPictureAll.toArray(new String[selectedPictureAll.size()]);
		if (!NetUtil.isNetworkConnected(bActivity))
		{
			new NoNetDialog(bActivity).show();
		}
		else
		{
			
			try
			{
				
				if (picPATHs.length > 6)
				{
					Utils.ToastShow(bActivity, "最多上传6张图片哦~");
				}
				else if (Utils.isEmpty(edtContent.getText().toString().trim()))
				{
					Utils.ToastShow(mContext, R.string.new_i_publish_content_empty);
				}
				else
				{
					if (edtContent.getText().toString().trim().length() > 140)
					{
						Utils.ToastShow(mContext, "不能超过140个字");
					}
					else
					{
						//						loadingDialog.show();
						showToast();
						btnSubmit.setEnabled(false);
						ActionHelp.addTopic(mContext, edtContent.getText().toString().trim(), new TextHttpResponseHandler()
						{
							
							@Override
							public void onSuccess(int statusCode, Header[] headers, String responseString) {
								//								loadingDialog.dismiss();
								success();
							}
							
							@Override
							public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
								//								loadingDialog.dismiss();
								closeToast(-1);
								btnSubmit.setEnabled(true);
								Log.i("errorCode:" + statusCode + " responseString:" + responseString);
								if (statusCode > 999)
								{
									JSONObject jsonObject;
									try
									{
										jsonObject = new JSONObject(responseString);
										String resultString = jsonObject.getString("returnObject");
										Utils.ToastShow(mContext, resultString);
									}
									catch (JSONException e)
									{
										Utils.ToastShow(mContext, "数据发布异常");
										e.printStackTrace();
									}
									
								}
							}
						}, picPATHs);
					}
					
				}
			}
			catch (FileNotFoundException e)
			{
				Utils.ToastShow(mContext, "发布失败");
				e.printStackTrace();
			}
		}
	}
	
	private void success() {
		closeToast(0);
		btnSubmit.setEnabled(true);
		Utils.ToastShow(mContext, "发布成功");
		MomentsPage.instance.contentItemView.getInteractionData(1);
		NewInteractionContentView.mapList5.clear();
		new Handler().postDelayed(new Runnable()
		{
			@Override
			public void run() {
				bActivity.onBackPressed();
			}
		}, 800);
	}
	
	private void notyPicChange() {
		if (selectedPictureAll.size() > 5)
		{
			addFriend.setVisibility(View.GONE);
		}
		else
		{
			addFriend.setVisibility(View.VISIBLE);
		}
		
	}
	
	private class FriendImageView
	        implements
	        OnClickListener
	{
		private View     friendView;
		public ImageView friendImg;
		public ImageView deleteImg;
		
		public String    imagePath = "";
		
		public FriendImageView(String imagePath) {
			friendView = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_center_user_publish_friend_item_img, friendLL, false);
			friendImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_img);
			friendImg.setOnClickListener(this);
			deleteImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_delete);
			deleteImg.setOnClickListener(this);
			this.imagePath = imagePath;
			ImageLoaderUtil.loadLocalUrl(imagePath, friendImg);
		}
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.new_interation_center_user_publish_friend_item_delete:
					remove();
					break;
				case R.id.new_interation_center_user_publish_friend_item_img:
					Intent atlasSeeIntent = new Intent(bActivity, NewInteractionAtlasSeeActivity.class);
					atlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_LOCALURL);
					atlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, selectedPictureAll);
					atlasSeeIntent.putExtra(DefaultConsts.NI_POSITION, listFriend.indexOf(this));
					bActivity.startActivity(atlasSeeIntent);
					break;
			}
			
		}
		
		public void remove() {
			listFriend.remove(this);
			selectedPictureAll.remove(imagePath);
			friendLL.removeView(friendView);
			notyPicChange();
		}
		
		public View getFriendView() {
			return this.friendView;
		}
		
	}
	
	private LoadToast    toast;
	private final String loadingLable = "正在发布...";
	
	/** LoadToast是否显示中 */
	public boolean isToastShowing() {
		return null != toast && toast.isShowing();
	}
	
	/** 显示LoadToast */
	public void showToast() {
		if (null == toast)
		{
			toast = new LoadToast(bActivity);
			toast.setText(loadingLable);
			toast.setTranslationY(height / 2 - 50).setBackgroundColor(Color.parseColor("#FFFFFF")).setProgressColor(Color.BLUE);
		}
		if (!isToastShowing()) toast.show();
	}
	
	/**
	 * 关闭LoadToast
	 * 
	 * @param type
	 *            0:关闭，1：成功，-1：错误
	 */
	public void closeToast(int type) {
		if (null == toast) return;
		switch (type) {
			case -1:
				toast.error();
				break;
			case 0:
				toast.close();
				toast = null;
				break;
			case 1:
				toast.success();
				break;
		}
	}
}
